﻿package component.validate.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import component.validate.config.DeleteValidatorInfo;
import component.validate.config.SaveValidatorInfo;
import component.validate.config.ValidatorInfo;
import component.validate.config.ValidatorMap;
import component.validate.dao.ConnectionFactory;
import component.validate.dao.IValidateConnection;
import component.validate.exception.ValidateException;
import component.validate.util.StringUtil;

public class ValidateServiceImpl implements IValidateService {
	
	public final static String TYPE_ADD = "1";

	public final static String TYPE_UPDATE = "2"; 

	public final static String TYPE_DELETE = "3";
	
	private IValidateConnection connectionUtil = ConnectionFactory.getConnectionUtil();
	
	private ValidatorInfo valInfo;
	
	public ValidateServiceImpl(String id) throws ValidateException{
		ValidatorInfo info = ValidatorMap.getInstance().getValidatorInfo(id);
		if (info == null) {
			throw new ValidateException(id + " 没有配置！ ");
		}
		this.valInfo = info;
	}
	
	private void close(ResultSet rs,PreparedStatement pstm) throws ValidateException{
		try {
			if (rs != null)
				rs.close();
			if (pstm != null)
				pstm.close();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new ValidateException(e);
		}
		connectionUtil.close();
	}
	
	private List[] getDataList(String[] sqls) throws ValidateException{
		Connection con = connectionUtil.getConnection();
		PreparedStatement pstm = null;
		ResultSet rs = null;
		List[] listArr = new ArrayList[sqls.length];
		try{
			for(int j=0;j<sqls.length;j++){
				List list = new ArrayList();
				pstm = con.prepareStatement(sqls[j]);
				rs = pstm.executeQuery();
				ResultSetMetaData rsMeta = rs.getMetaData();
				int columnCount = rsMeta.getColumnCount();
				while(rs.next()){
					Object[] objs = new Object[columnCount];
					for(int i=1;i<=columnCount;i++){
						objs[i-1] = rs.getObject(i);
					}
					list.add(objs);
				}
				listArr[j] = list;
			}
		}catch(SQLException e){
			e.printStackTrace();
			throw new ValidateException(e);
		}
		finally{
			this.close(rs, pstm);
		}
		return listArr;
	}
	
	public String checkSaveUnique(Object[] valFieldValues,Object[] conditionValues) throws ValidateException{
		List saveValList = valInfo.getSaveValList();
		if(saveValList == null || saveValList.isEmpty()){
			throw new ValidateException("没有配置保存验证...");
		}
		SaveValidatorInfo saveValInfo = (SaveValidatorInfo)saveValList.get(0);
		if(!StringUtil.isNull(saveValInfo.getSql())){//配置了sql
			String[] sqlArr = valInfo.getSaveValSql(conditionValues);
			List[] listArr = this.getDataList(sqlArr);
			String msg = "true";
			for(int i = 0;i<listArr.length;i++){
				saveValInfo = (SaveValidatorInfo)saveValList.get(i);
				List list = listArr[i];
				int rows = Integer.parseInt(String.valueOf(((Object[])list.get(0))[0]));
				if(rows != 0) return saveValInfo.getMsg();
			}
			return msg;
		}else{
			String[] sqlArr = valInfo.getSaveValSql(conditionValues);
			List[] listArr = this.getDataList(sqlArr);
			if(listArr==null || listArr.length==0) return "true";
			
			String returnMsg = "true";
			int size = sqlArr.length;
			for(int k=0;k<size;k++){
				List list = listArr[k];
				//if(list==null || list.isEmpty()) return "true";
				
				Object[] valFieldValues2 = valFieldValues;
				if(size>1){//如果是多个验证,valFieldValues就是二维数组
					valFieldValues2 = (Object[])valFieldValues[k];
				}
				Object idValue = valFieldValues2[0];
				//valFieldValues2第一个元素为id值,如果id不为空就是修改时的验证(不与本身比较,需要去掉本身)
				if(!StringUtil.isNull(String.valueOf(idValue))){
					for(int i=0;i<list.size();i++){
						Object[] objs = (Object[])list.get(i);
						if(objs[0].equals(idValue)){
							list.remove(i);
							break;
						}
					}
				}
				
				for(int i=0;i<list.size();i++){
					Object[] objs = (Object[])list.get(i);
					//从第二个元素开始才是验证字段的值
					for(int j=1;j<objs.length;j++){
						if(!StringUtil.isNull(String.valueOf(valFieldValues2[j]))){//不为空才验证
							//System.out.println("数据库的值 = " + objs[j] + ",页面的值 = " + valFieldValues2[j]);
							if(String.valueOf(objs[j]).trim().equals(String.valueOf(valFieldValues2[j]))){
								returnMsg = "";
								String msg = ((SaveValidatorInfo)valInfo.getSaveValList().get(k)).getMsg();
								if(msg.indexOf("#")==-1){
									returnMsg += msg;
								}else{
									String[] msgArr = msg.split("#");
									String[] valNameArr = msgArr[0].split(",");
									returnMsg += valNameArr[j-1] + msgArr[1];
								}
							}
						}
					}
				}
			}
			return returnMsg;
		}
	}
	

	public String checkDeleteAssociation(Object[] idFieldValues,Object[] conditionValues) throws ValidateException {
		Map sqlMap = valInfo.getDeleteValSql(idFieldValues,conditionValues);
		List deleteValList = valInfo.getDeleteValList();
		
		Connection con = connectionUtil.getConnection();
		PreparedStatement pstm = null;
		ResultSet rs = null;
		Map msgMap = new HashMap();
		try{
			for(int j=0;j<idFieldValues.length;j++){
				String[] sqls = (String[])sqlMap.get(idFieldValues[j]);
				for (int i = 0; i < sqls.length; i++) {
					String sql = sqls[i];
					pstm = con.prepareStatement(sql);
					rs = pstm.executeQuery();
					if (rs.next()) {
						int rscount = rs.getInt(1);
						if (rscount > 0) {
							//String msg = ((DeleteValidaterInfo)deleteValList.get(i)).getMsg();
							//this.setMsg("您选择的第 "+(j+1)+" 条记录"+msg);
							//this.setMsg("您选择的部分记录"+msg);
							//flag = false;
							//return flag;
							Integer key = new Integer(i);
							String value = (String)msgMap.get(key);
							if(value==null) value="";
							value += (j+1) + ",";
							msgMap.put(key, value);
						}
					}
				}
			}
		}catch(SQLException e){
			e.printStackTrace();
			throw new ValidateException(e);
		}
		finally{
			this.close(rs, pstm);
		}
		if(msgMap.isEmpty()){
			return "true";
		}else{
			String msgs = "";
			Set set = msgMap.keySet();
			Iterator iter = set.iterator();
			while(iter.hasNext()){
				Integer key = (Integer)iter.next();
				String value = (String)msgMap.get(key);
				value = value.substring(0, value.length()-1);
				String msg = ((DeleteValidatorInfo)deleteValList.get(key.intValue())).getMsg();
				msgs += "您选择的第 " + value + " 条记录" + msg + "\n";
			}
			return msgs;
		}
	}
	
	
	public static void main(String[] args) {
		Integer int1 = new Integer(10);
		String str1 = "10";
		System.out.println(String.valueOf(int1).equals(str1));
	}
}
